var app = getApp();
var utils = require("../../utils/util.js");
Page({
  data: {
    //图片
    picList: [],
    //视频
    videoResource: null,
    //是否有视频
    isChooseVideo: false,
    //宠物介绍
    petDescribe: '',
    //绝育
    sterilization: 0,
    //疫苗
    vaccine: 0,
    //驱虫
    expelling: 0,
    //要求列表
    claimList: [""],
    //弹窗提示
    toasthidden: true,
    toastTitle: '提示',
    toastContent: '您选择的视频已经超过15秒啦, 请重新选择',
    toastConfirm: '确定',
    formId: ''

  },
  onLoad: function(options) {
    this.setData({
      statusBarHeight: app.globalData.systemInfo.statusBarHeight + 15
    })
    this.getCookie();
  },
  onShow: function() {
    this.setData({
      randomNumber: Math.random()
    })
  },

  //读取缓存
  getCookie: function() {
    var addGivePet = wx.getStorageSync("addGivePet");
    if (addGivePet != '') {
      var that = this;
      var addGivePet = JSON.parse(addGivePet);
      wx.showModal({
        title: '提示',
        content: '是否继续编写保存的草稿',
        cancelText: '重写',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#627096',
        success: function(e) {
          if (e.confirm) {
            that.setData({
              picList: addGivePet.picList,
              videoResource: addGivePet.videoResource,
              petDescribe: addGivePet.petDescribe,
              sterilization: addGivePet.sterilization,
              vaccine: addGivePet.vaccine,
              expelling: addGivePet.expelling,
              claimList: addGivePet.claimList,
              isChooseVideo: addGivePet.videoResource == null ? false : true,
            })
          }
          if (e.cancel) {
            that.setData({
              picList: [],
              videoResource: {},
              petDescribe: '',
              sterilization: 0,
              vaccine: 0,
              expelling: 0,
              claimList: [],
              isChooseVideo: false
            })
            wx.clearStorage("addGivePet");
          }
        }
      })
    }
  },
  //缓存读取失败
  loadError: function() {
    this.setData({
      picList: [],
      videoResource: {},
      petDescribe: '',
      sterilization: 0,
      vaccine: 0,
      expelling: 0,
      claimList: [],
    })
    wx.clearStorage("addGivePet");
  },
  //关闭弹窗
  toastConfirm: function() {
    this.setData({
      toasthidden: true
    })
  },


  //发布
  getPolicy: function(e) {
    this.data.formId = e.detail.formId;
    var picList = this.data.picList;
    var petDescribe = this.data.petDescribe;
    var videoResource = this.data.videoResource;
    var sterilization = this.data.sterilization;
    var vaccine = this.data.vaccine;
    var expelling = this.data.vaccine;
    var claimList = this.data.claimList;
    if (picList.length == 0) {
      wx.showToast({
        title: '请至少上传一张宠物照片',
        icon: 'none',
        duration: 3000
      })
      return;
    }

    if (petDescribe == '') {
      wx.showToast({
        title: '请填写宠物描述',
        icon: 'none',
        duration: 3000
      })
      return;
    }



    if (claimList.length == 1) {
      if (claimList[0] == '') {
        wx.showToast({
          title: '请填写领养要求',
          icon: 'none',
          duration: 3000
        })
        return;
      }
    }
    wx.showToast({
      title: '正在努力发布.',
      icon: 'loading',
      duration: 3000,
      mask: true
    })
    //延迟跳转
    var timeout = setTimeout(function() {
      that.rollback();
      clearTimeout(timeout);
    }, 3000)
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getUploadFileOssPolicy',
      method: 'GET',
      data: {
        userId: app.globalData.user.id,
        type: 4
      },
      success: function(r) {
        if (r.data.code == 200) {
          that.upload(r.data.data, picList, 0);
        } else {
          that.errCookie();
        }
      },
      fail: function() {
        that.errCookie();
      }
    })
  },

  //上传视频
  uploadVideo: function(policyData) {
    var videoResource = this.data.videoResource;
    var mimeType = utils.getMimeType(videoResource.tempFilePath);
    //生成名称
    var uuid = utils.getUUID();
    var src = uuid + mimeType;
    var that = this;
    wx.uploadFile({
      url: policyData.host,
      filePath: videoResource.tempFilePath,
      name: 'file',
      formData: {
        key: src,
        policy: policyData.policy,
        OSSAccessKeyId: policyData.accessid,
        success_action_status: '200',
        signature: policyData.signature
      },
      success: function() {
        that.data.videoResource.src = policyData.host + src;
        that.addGivePet();
      },
      fail() {
        that.errCookie();
      }
    })
  },
  //发布
  addGivePet: function() {
    var formId = this.data.formId;
    var picList = this.data.picList;
    var petDescribe = this.data.petDescribe;
    var videoResource = this.data.videoResource;
    var sterilization = this.data.sterilization;
    var vaccine = this.data.vaccine;
    var expelling = this.data.vaccine;
    var claimList = this.data.claimList;
    var adoptClaim = '';
    for (var i = 0; i < claimList.length; i++) {
      if (claimList[i] != '') {
        if (i == claimList.length - 1) {
          adoptClaim += claimList[i];
        } else {
          adoptClaim += claimList[i] + ',';
        }
      }
    }
    var urlList = [];
    for (var i of picList) {
      if (i.src != null) {
        var resource = {
          src: i.src,
          sequence: i.sequence,
          width: i.width,
          height: i.height
        }
        urlList.push(resource);
      }
    }
    if (videoResource != null) {
      var resource = {
        src: videoResource.src,
        sequence: urlList.length + 1,
        width: videoResource.width,
        height: videoResource.height,
        size: videoResource.duration
      }
      urlList.push(resource);
    }

    wx.request({
      url: app.globalData.requestUrl + 'addGivePet',
      method: 'POST',
      data: {
        userId: app.globalData.user.id,
        petDescribe: petDescribe,
        adoptClaim: adoptClaim,
        sterilization: sterilization,
        vaccine: vaccine,
        expelling: expelling,
        province: app.globalData.user.province,
        city: app.globalData.user.city,
        district: app.globalData.user.district,
        address: app.globalData.user.address,
        formId: formId,
        urlList: urlList
      }
    })
  },
  //上传图片
  upload: function(policyData, picList, index) {
    var that = this;
    //图片上传完毕
    if (!(index < picList.length)) {
      if (that.data.videoResource == null) {
        that.addGivePet();
        return;
      } else {
        that.uploadVideo(policyData);
        return;
      }
    }


    //生成名称
    var uuid = utils.getUUID();
    //获取类型
    var mimeType = utils.getMimeType(picList[index].path);
    var src = uuid + mimeType

    wx.uploadFile({
      url: policyData.host,
      filePath: picList[index].path,
      name: 'file',
      formData: {
        key: src,
        policy: policyData.policy,
        OSSAccessKeyId: policyData.accessid,
        success_action_status: '200',
        signature: policyData.signature
      },
      //成功要递归操作
      success: function(r) {
        if (r.statusCode == 200) {
          picList[index].src = policyData.host + src;
          picList[index].sequence = index + 1;
          //递归调用
          that.upload(policyData, picList, index + 1);
        } else {
          picList[index].src = null;
          picList[index].sequence = index + 1;
          //递归调用
          that.upload(policyData, picList, index + 1);
        }

      },
      fail: function() {
        that.errCookie();
      },
    })
  },

  //失败存草稿
  errCookie: function() {
    var addGivePet = {
      picList: this.data.picList,
      videoResource: this.data.videoResource,
      petDescribe: this.data.petDescribe,
      pet: this.data.pet,
      sterilization: this.data.sterilization,
      vaccine: this.data.vaccine,
      expelling: this.data.expelling,
      claimList: this.data.claimList
    }
    wx.setStorage({
      key: 'addGivePet',
      data: JSON.stringify(addGivePet),
      success: function() {
        wx.showToast({
          title: '发布失败已帮您成功存稿',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  //存草稿
  cookie: function() {
    var addGivePet = {
      picList: this.data.picList,
      videoResource: this.data.videoResource,
      petDescribe: this.data.petDescribe,
      sterilization: this.data.sterilization,
      vaccine: this.data.vaccine,
      expelling: this.data.expelling,
      claimList: this.data.claimList
    }
    wx.setStorage({
      key: 'addGivePet',
      data: JSON.stringify(addGivePet),
      success: function() {
        wx.showToast({
          title: '已帮您成功存稿',
        })
      }
    })
  },

  //添加要求
  addClaim: function() {
    var claimList = this.data.claimList;
    claimList.push('');
    this.setData({
      claimList: claimList
    })
  },
  //输入要求
  claimInput: function(e) {
    var claimList = this.data.claimList;
    //当前输入数量
    var cursor = e.detail.cursor;
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    // //不能超过50
    if (cursor > 50) {
      value = value.substring(0, 50);
    }
    claimList[index] = value;
    this.setData({
      claimList: claimList
    })
  },




  //删除要求
  dropClaim: function(e) {
    var index = e.currentTarget.dataset.index;
    var claimList = this.data.claimList;
    claimList.splice(index, 1);
    this.setData({
      claimList: claimList
    })
  },
  //是否绝育
  sterilization: function(e) {
    this.setData({
      sterilization: e.currentTarget.dataset.id
    })
  },
  //疫苗
  vaccine: function(e) {
    this.setData({
      vaccine: e.currentTarget.dataset.id
    })
  },
  //驱虫
  expelling: function(e) {
    this.setData({
      expelling: e.currentTarget.dataset.id
    })
  },
  //删除照片
  dropPic: function(e) {
    var index = e.currentTarget.dataset.index;
    var picList = this.data.picList;
    picList.splice(index, 1);
    this.setData({
      picList: picList
    })
  },

  //添加照片
  addPic: function() {
    var that = this;
    wx.chooseImage({
      count: 4 - that.data.picList.length,
      success: function(r) {
        var list = [];
        for (var i of r.tempFiles) {
          var pic = {
            path: i.path,
            src: '',
            sequence: 0,
            width: 0,
            height: 0
          }
          list.push(pic);
        }
        //给一个URL属性.
        that.setData({
          picList: that.data.picList.concat(list)
        })
      },
    })
  },

  //加载图片
  loadPic: function(r) {
    var index = r.currentTarget.dataset.index;
    var picList = this.data.picList;
    var pic = picList[index];
    pic.width = r.detail.width;
    pic.height = r.detail.height;
    this.setData({
      picList: picList
    })
  },

  //选择视频
  chooseVideo: function() {
    var isChooseVideo = this.data.isChooseVideo;
    //如果是重新选择视频,需要清除上次的全部状态
    if (isChooseVideo) {
      this.setData({
        //是否已经选择视频
        isChooseVideo: false,
        //视频资源
        videoResource: null,
      })
    }
    var that = this;
    wx.chooseVideo({
      maxDuration: 15,
      success: function(res) {
        var duration = parseInt(res.duration);
        //如果视频大于5分钟,提示超过最长限制
        if (duration > 15) {
          that.setData({
            toasthidden: false
          })
        } else {
          that.setData({
            videoResource: res,
            isChooseVideo: true
          })
        }
      }
    })
  },

  //输入文字
  inputDescribe: function(e) {
    //当前输入数量
    var cursor = e.detail.cursor;
    var value = e.detail.value;
    //不能超过500
    if (cursor > 500) {
      this.setData({
        petDescribe: value.substring(0, 500)
      })
    } else {
      this.setData({
        petDescribe: value
      })
    }
  },

  //返回下一个页面
  rollback: function() {
    wx.navigateBack({
      delta: 1
    })
  }
})